package com.dimbottom.controller.handler.exception;

import com.dimbottom.entity.rest.Rest;
import com.dimbottom.entity.rest.RestBody;
import com.dimbottom.entity.rest.Code;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ResponseBody
@ControllerAdvice
public class BadValidExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Rest<Void> validExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        RestBody<Void> errMsg = new RestBody<>(Code.Invalid);
        fieldErrors.forEach(fieldError -> errMsg.setErrors(fieldError.getDefaultMessage()));
        errMsg.setCode(400);
        return errMsg;
    }

}
